<template>
  <div class="subject-content">
    <el-form :model="queryParams" size="medium" ref="queryForm" label-width="75px">

      <el-form-item label="用户名称" prop="nickName" size="mini">
        <el-input v-model="queryParams.nickName" clearable placeholder="请输入用户名称" @keyup.enter.native="searchQuery"></el-input>
      </el-form-item>

      <el-form-item label="账号" prop="userName" size="mini">
        <el-input v-model="queryParams.userName" clearable placeholder="请输入账号" @keyup.enter.native="searchQuery"></el-input>
      </el-form-item>

      <el-form-item label="IP" prop="loginIp" size="mini">
        <el-input v-model="queryParams.loginIp" clearable placeholder="请输入IP" @keyup.enter.native="searchQuery"></el-input>
      </el-form-item>

      <el-form-item size="mini">
        <el-button type="primary" icon="el-icon-search" @click="searchQuery">提交</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" style="margin-bottom: 15px">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" @click="rowDeleteList" size="mini">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading" @click="exportExcel">导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="userList" border style="width: 100%;" :cell-style="{padding:'0'}" :row-style="{height:'10px'}"  @selection-change="handleSelectionChange">
      <el-table-column fixed="left" type="selection" width="50" align="center"></el-table-column>
      <el-table-column fixed="left" prop="userId" width="80" label="ID" sortable align="center"></el-table-column>
      <el-table-column prop="userName" label="账号" width="200" sortable></el-table-column> <!--sortable 排序-->
      <el-table-column prop="nickName" label="用户名称" width="200" sortable align="center"></el-table-column>
      <el-table-column label="用户头像" width="180" sortable align="center">
        <template v-slot="scope">
          <img :src="img(scope.row.avatar)" style="height: 40px;width: 40px"/>
        </template>
      </el-table-column>
      <el-table-column prop="userEmail" label="邮箱" width="200" sortable align="center"></el-table-column>
      <el-table-column prop="phonenumber" label="手机号" width="150" sortable align="center"></el-table-column>
      <el-table-column label="性别" width="120" sortable align="center">
        <template v-slot="scope">
          <dictTag :options="dict.dictType.user_sex" :value="scope.row.userSex"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="120" align="center">
        <template v-slot="scope">
          <dictTag :options="dict.dictType.user_status" :value="scope.row.userStatus"/>
        </template>
      </el-table-column>
      <el-table-column prop="loginIp" label="最后登录IP" width="150" sortable align="center"></el-table-column>
      <el-table-column fixed="right" label="操作" width="150" align="center">
        <!-- 固定列需要使用fixed属性，它接受 Boolean 值或者left right，表示左边固定还是右边固定。 -->
        <template slot-scope="scope">
          <el-button type="text" size="small" icon="el-icon-edit" @click="rowUpdate(scope.row)">修改</el-button>
          <el-button type="text" size="small" icon="el-icon-delete" @click="rowDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <page
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.current"
        :limit.sync="queryParams.size"
        @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>

      <el-form ref="userForm" :model="userForm" :rules="rules" size="small" label-width="300px">

        <el-form-item label="用户名称" prop="nickName">
          <el-input v-model="userForm.nickName" placeholder="请输入用户名称" clearable></el-input>
        </el-form-item>

        <el-form-item label="账号" prop="userName">
          <el-input v-model="userForm.userName" placeholder="请输入账号" clearable></el-input>
        </el-form-item>

        <el-form-item v-if="userForm.userId == undefined" label="密码" prop="password">
          <el-input v-model="userForm.password" placeholder="请输入单行文本密码" clearable show-password></el-input>
        </el-form-item>

        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="userForm.roleIds" multiple placeholder="请选择" @change="changeValue()">
            <el-option v-for="(item, index) in roleOptions" :key="index" :label="item.roleName" :value="item.roleId"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="性别" prop="userSex">
          <el-radio-group v-model="userForm.userSex" size="medium">
            <el-radio v-for="(item, index) in dict.dictType.user_sex" :key="index" :label="item.dictValue">
              {{ item.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="userForm.userType" placeholder="请选择用户类型" clearable>
            <el-option v-for="(item, index) in dict.dictType.user_type" :key="index" :label="item.dictLabel" :value="item.dictValue"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="账号状态" prop="status">
          <el-radio-group v-model="userForm.userStatus" size="medium">
            <el-radio v-for="(item, index) in dict.dictType.user_status" :key="index" :label="item.dictValue">
              {{ item.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="userForm.userEmail" placeholder="请输入单行文本邮箱" clearable></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="userForm.phonenumber" placeholder="请输入单行文本手机号" clearable></el-input>
        </el-form-item>

        <el-form-item label="头像" prop="avatar">
          <el-upload
              ref="upload"
              list-type="picture-card"
              accept="image/*"
              action="#"
              :http-request="requestUpload"
              :file-list="fileList"
              :auto-upload="true"
              :before-upload="avatarBeforeUpload"
              :on-change="onChange">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>
import {getUserList, selectUserById, deletUserByIds, deletUserById, userExportExcel, updateUser, addUser} from '@/api/admin/user'
import {selectRole} from '@/api/admin/role'
import Page from "@/views/components/page";
import {upload} from "@/api/admin/common";
import dictTag from "@/views/components/dictTag";

export default {
  name: 'user',
  dicts:["user_sex","user_type","user_status"],
  components: {Page,dictTag},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: "",
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      //表格数据
      userList: [],
      // 查询参数  current 当前页   size 页大小
      queryParams: {
        current: 1,
        size: 10,
        nickName: undefined,
        userName: undefined,
        loginIp: undefined
      },
      // 添加、修改提交表单
      userForm: {},
      //上传图片
      fileList:[],
      // 表单数据校验
      rules: {
        nickName: [{
          required: true,
          message: '请输入用户名称',
          trigger: 'blur'
        }],
        userName: [{
          required: true,
          message: '请输入账号',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }],
        roleIds: [{
          required: true,
          type: "array",
          message: '请至少选择一个角色',
          trigger: 'change'
        }],
        userType: [{
          required: true,
          message: '请选择用户类型',
          trigger: 'change'
        }],
        userEmail: [{
          pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
          message: '邮箱格式错误',
          trigger: 'blur'
        }],
        phonenumber: [{
          pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
          message: '请填写正确的手机号',
          trigger: 'blur'
        }],
      },
      // 表单 角色 下拉框 数据
      roleOptions: [],
    }
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      getUserList(this.queryParams).then(res => {
        this.userList = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      })
    },
    /** 搜索按钮操作 */
    searchQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.searchQuery();
    },
    /** 表单重置 */
    reset() {
      this.userForm = {
        userId: undefined,
        nickName: undefined,
        userName: undefined,
        password: undefined,
        roleIds: [],
        userSex: undefined,
        userType: undefined,
        userEmail: undefined,
        phonenumber: undefined,
        userStatus: undefined,
        avatar: undefined
      };
      this.resetForm("userForm");
    },
    /** 角色下拉框的值 */
    getRoleOptions(){
      selectRole().then(res=>{
        this.roleOptions = res.data
      })
    },
    /** 头工具栏--添加 */
    handleAdd() {
      this.getRoleOptions()
      this.reset();
      this.title = "添加用户";
      this.userForm.roleIds= [1];
      this.userForm.userSex="0";
      this.userForm.userType="0";
      this.userForm.userStatus="0";
      this.userForm.avatar="/ly/ly-images/凌云.png";
      this.fileList=[{url:require('/ly/ly-images/凌云.png')}]
      this.open = true;
    },
    /** 头工具栏--修改 */
    handleUpdate(){
      if (this.ids.length === 0) {
        this.$modal.msgWarning('请选择要修改的用户！')
      }else if(this.ids.length >1){
        this.$modal.msgWarning('请选择一个用户进行修改！')
      }else{
        this.getRoleOptions()
        this.reset();
        const userId = this.ids
        selectUserById(userId).then(res =>{
          this.userForm = res.data;
          this.userForm.roleIds = res.roleIds;
          this.fileList=[{url:this.img(this.userForm.avatar)}]
          this.title = "修改用户";
          this.open = true;
        })
      }
    },
    /** 头工具栏--删除*/
    rowDeleteList() {
      if (this.ids.length === 0) {
        this.$modal.msgWarning('请选择要删除的用户！')
      } else {
        const userIds = this.ids
        this.$modal.confirm('是否确认删除？').then(function () {
          return deletUserByIds(userIds)
        }).then(res => {
          this.getList();
          this.$modal.msgSuccess(res.msg);
        });
      }
    },
    /** 头工具栏--excel导出*/
    exportExcel(){
      this.$modal.confirm('是否导出当前搜索结果？').then(() => {
        this.exportLoading = true;
        return userExportExcel(this.queryParams)
      }).then(res => {
        this.$download.name(res.data);
        this.exportLoading = false;
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          if (this.userForm.userId != undefined) {
            updateUser(this.userForm).then(res=>{
              this.$modal.msgSuccess(res.msg);
              this.open = false;
              this.getList();
            })
          } else {
            addUser(this.userForm).then(res => {
              this.$modal.msgSuccess(res.msg);
              this.open = false;
              this.getList();
            })
          }
        }
      });
    },
    /**取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 行工具栏--删除 */
    rowDelete(row) {
      const userId = row.userId
      this.$modal.confirm('是否确认删除？').then(function () {
        return deletUserById(userId)
      }).then(res => {
        this.getList();
        this.$modal.msgSuccess(res.msg);
      });
    },
    /** 行工具栏--修改*/
    rowUpdate(row) {
      this.getRoleOptions()
      this.reset();
      const userId = row.userId
      selectUserById(userId).then(res =>{
        this.userForm = res.data;
        this.userForm.roleIds = res.roleIds;
        this.fileList=[{url:this.img(this.userForm.avatar)}]
        this.title = "修改用户";
        this.open = true;
      })
    },
    /** 路径拼接 */
    img(url) {
      return process.env.VUE_APP_BASE_API + url
    },
    /**多选框选中数据*/
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
    },
    /** 自定义图片上传接口*/
    requestUpload(obj){
      let formData = new FormData();
      formData.append("file", obj.file);
      upload(formData).then(res=>{
        this.userForm.avatar = res.data
        this.$modal.msgSuccess(res.msg);
      })
    },
    /** 表单提交 图片大小 格式验证*/
    avatarBeforeUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isLt5M;
    },
    /** 图片状态改变时触发(只上传一张图片，上传第二张时会覆盖第一张图片)*/
    onChange(res, file) {
      if (file.length > 1) {
        file.splice(0, 1);  //在位置 0，删除 1 个项目：
      }
    },
    /** 解决多选下拉框点击后无法刷新*/
    changeValue(){
      this.$forceUpdate()
    },
  },
  created() { // 初始化
    this.getList();
  },
}
</script>

<style scoped>
.subject-content {
}
.el-row {
  display: inline-block;
}
.el-form-item {
  display: inline-block;
}
</style>





